#include <iostream>
#include <stdlib.h>

using namespace std;

const int N = 20;

int e[N], ne[N];
int n = 0;

int next(int x)
{
    return ne[x];
}

void init()
{
    for (int i = 0; i < N - 2; i++)
        ne[i] = i + 1;
    ne[N - 2] = ne[N - 1] = 0;
}

int malloc_ssl()
{
    if (next(0) == 0)
    {
        printf("无空间可分配\n");
        exit(EXIT_FAILURE);
    }
    n++;
    int first_space = next(0);
    ne[0] = next(first_space);
    return first_space;
}

void insert_to_kback(int k_index, int x)
{
    int space = malloc_ssl();
    e[space] = x;
    ne[space] = next(k_index);
    ne[k_index] = space;
}

void insert(int k, int x)
{
    if (!(n <= N - 2 && k >= 0 || k <= n))
    {
        printf("错误: 空间满了, 怎么插入?\n");
        exit(EXIT_FAILURE);
    }
    int head = N - 1;
    for (int i = 1; i <= k; i++)
        head = next(head);
    insert_to_kback(head, x);
}

void free_ssl(int k)
{
    n--;
    ne[k] = next(0);
    ne[0] = k;
}

void erase_of_kback(int k)
{
    int knext = next(k);
    ne[k] = next(knext);
    free_ssl(knext);
}

int erase(int k)
{
    if (!(n > 0 && k >= 0 && k < n))
    {
        printf("错误: 没有元素, 怎么删除?\n");
        exit(EXIT_FAILURE);
        return ~(1 << 31); // 2147483647
    }
    int head = N - 1;
    for (int i = 1; i <= k; i++)
        head = next(head);
    erase_of_kback(head);
    return e[next(head)];
}

void show()
{
    int head = N - 1;
    for (int i = 1; i <= n; i++)
    {
        head = next(head);
        printf("%d ", e[head]);
    }
    printf("\n");
}

int main(void)
{
    init();
    for (int i = 1; i <= 18; i++)
        insert(0, i);
    show();
    for (int i = 1; i <= 18; i++)
        erase(0);
    show();

    for (int i = 1; i <= 8; i++)
        insert(0, i);
    show();

    erase(0); erase(0); erase(0);
    show();

    for (int i = 1; i <= 8; i++)
        insert(0, i);
    show();
}